<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\db\exception\BindParamException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;

/**
 * 教师工资单
 *
 * @icon fa fa-circle-o
 */
class Salary extends Backend
{

    /**
     * Salary模型对象
     * @var \app\admin\model\Salary
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Salary;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->alias('a')
            ->join(['fa_teacher' => 'b'], 'a.user_id = b.id', 'left')
            ->where($where)
            ->order($sort, $order)
            ->field('a.*, b.name')
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fields = [
            'staff_number',
            'name',
            'probation',
            'post_salary',
            'salary',
            'subtotal_1',
            'special_salary',
            'basic_salary',
            'post_subsidy',
            'subtotal_2',
            'life_salary',
            'rescue_salary',
            'only_child_salary',
            'subtotal_3',
            'reserve',
            'class_salary',
            'surplus_salary',
            'job_salary',
            'up_1360',
            'check_work_salary',
            'buckle_class_salary',
            'post_subsidy_salary',
            'subtotal_4',
            'reissue_salary',
            'subtotal_5',
            'fund_salary',
            'repair_fund_salary',
            'medical_salary',
            'repair_medical_salary',
            'old_salary',
            'repair_old_salary',
            'occupation_salary',
            'repair_occupation_salary',
            'subtotal_6',
            'total_1',
            'expense_deduction',
            'taxable_income',
            'tax_rate',
            'personal_tax',
            'repair_personal_tax',
            'issued_amount',
            'two_stickers',
            'base_salary',
            'boss_salary',
            'rank_salary',
            'best_salary',
            'basic_merits_salary',
            'house_salary',
            'total'
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            for ($currentRow = 6; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }

                $data = [];
                foreach ($values as $k => $v) {
                    $data[$fields[$k]] = $v;
                }
                $insert[] = $data;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            $title = $currentSheet->getCellByColumnAndRow(1, 1)->getValue();
            $isMatched = preg_match('/\d{2}(月)/', $title, $matches);

            foreach ($insert as $item => $value) {
                $teacher = \app\admin\model\Teacher::get([
                    'name' => $value['name']
                ]);
                // 获取用户id
                if (!$teacher) {
                    throw new Exception('没有【' . $value['name'] . '】的记录');
                }

                $insert[$item]['user_id'] = $teacher['id'];
                unset($insert[$item]['name']);

                $insert[$item]['salary_month'] = $matches[0];
                $insert[$item]['send_time'] = date('Y-m-d H:i:s');
            }

            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
